%%% Normalizes image values between 0 and 1 or normalizes a 3-d image stack,
%%% slice by slice.  Can also threshold an upper percentile and
%%% lower percentile of data points before normalization.
%%% Emily King
%%% Last updated: Dec 2, 2009

% To do: Add error checking

% Examples of use: 
% NormIm = imnorm(trees); -> NormIm is the normalization of the image trees
% between 0 and 1
% NormIm = imnorm(trees, 1, 2); -> The smallest 1% and the biggest 2% are
% (hard) tresholded and then the image is normalized.
% NormIm = imnorm(tree_stack); -> NormIm is the normalization of each slice 
% of the image stack tree_stack between 0 and 1
% NormIm = imnorm(tree_stack, 1, 2); -> The smallest 1% and the biggest 2% of each 
% slice of the image stack tree_stack are(hard) tresholded and then each slice is normalized.

% Note: requires Statistics Toolbox

function norm_image = imnorm(image,percentileMin,percentileMax)

if(nargin==1) % The default is no tresholding.
    percentileMin = 0;
    percentileMax = 0;
end

if((nargin==3)||(nargin==1))
    
    if(ndims(image)==2)
        norm_image = percNorm(image,percentileMin,percentileMax);
    end

    if(ndims(image)==3)
        norm_image = image;
        for i=1:size(image,3)
            norm_image(:,:,i) = percNorm(norm_image(:,:,i),percentileMin,percentileMax);
        end
    end
end

end

function norm_slice = percNorm(im,pMin,pMax)

vec_image = im(:);
pMinMax = prctile(vec_image,[pMin 100 - pMax]);
Min = pMinMax(1); Max = pMinMax(2);

thresh_im = im;
thresh_im(thresh_im < Min) = Min;
thresh_im(thresh_im > Max) = Max;

norm_slice = (thresh_im - Min)/(Max - Min);

end
